import express from 'express'
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

const app = express()

const port = 3000

app.use(express.json())

//查找所有
app.get('/', async (req, res) => {
  const data = await prisma.user.findMany({
    include: {
      posts: true,
    },
  })
  res.send(data)
})
//查找每一个用户
app.get('/user/:id', async (req, res) => {
  const row = await prisma.user.findMany({
    where: {
      id: Number(req.params.id),
    },
  })
  res.send(row)
})

// 创建
app.post('/create', async (req, res) => {
  const { name, email } = req.body
  const count = await prisma.user.count({
    where: {
      email: email,
    },
  })
  if (count) {
    res.send('不能创建相同的用户')
    return
  }

  const data = await prisma.user.create({
    data: {
      name,
      email,
      posts: {
        create: [
          {
            title: '文章1',
            content: '文章一内容',
          },
          {
            title: '文章1',
            content: '文章一内容',
          },
        ],
      },
    },
  })
  res.send(data)
})

// 查询
app.get('/', async (req, res) => {
  const data = await prisma.user.findMany({
    include: {
      posts: true,
    },
  })
  res.send(data)
})
// 单条查询
app.get('/user/:id', async (req, res) => {
  const { id } = req.params
  const data = await prisma.user.findMany({
    where: {
      id: Number(id),
    },
  })
  res.send(data)
})
// 更新单条
app.post('/update', async (req, res) => {
  const { name, email, id } = req.body
  const count = await prisma.user.count({
    where: {
      id: Number(id),
    },
  })
  if (!!!count) {
    res.send('请检查参数')
    return
  }
  const data = await prisma.user.update({
    data: {
      name,
      email,
    },
    where: {
      id: Number(id),
    },
  })
  res.send(data)
})

app.listen(port, () => {
  console.log(`端口:${port}已开启`)
})
